﻿#region Copyright 
/*-------------------------------------------------------------------------
* 命名空间名称/文件名:    SSPivot.Authorization/JwtHelper 
* CLR版本:     4.0.30319.42000
* 机器名称:    DESKTOP-NHMLO8A
* 功 能：       N/A
* 类 名：       JwtHelper
* 创建时间：  2025/5/24 11:31:59
* 版本号：      v1.0
* 创建人:        xulong
*-------------------------------------------------------------------------*/
#endregion
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;
using SSPivot.AspNetCore.Abstractions.User;
using SSPivot.Authorization.Authorize;
using SSPivot.Authorization.User;
using SSPivot.Common.Helpers;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace SSPivot.Authorization
{
    public enum TokenType
    {
        AccessToken = 1,
        RefreshToken = 2
    }
    public class JwtHelper
    {
        /// <summary>
        /// 获取用户身份信息
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        //public static ICurrentUser GetLoginUser(HttpContext httpContext)
        //{
        //    string token = httpContext.Request.Headers[GlobalConfigAuthorization.AuthorizationHeader];

        //    if (!string.IsNullOrEmpty(token))
        //    {
        //        return ValidateJwtToken(ParseToken(token));
        //    }
        //    return null;
        //}
        public static string CreateToken(JwtConfig jwtConfig, Claim[] claims, TokenType tokenType)
        {
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.SecurityKey));

            string issuer = jwtConfig.Issuer;
            string audience = tokenType.Equals(TokenType.AccessToken) ? jwtConfig.Audience : jwtConfig.RefreshTokenAudience;
            int expires = tokenType.Equals(TokenType.AccessToken) ? jwtConfig.Expire : jwtConfig.RefreshTokenExpire;

            var token = new JwtSecurityToken(
                issuer: issuer,
                audience: audience,
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddMinutes(expires),
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
            );

            var jwtAccessTokenToken = new JwtSecurityTokenHandler().WriteToken(token);
            return jwtAccessTokenToken;
        }
        public ClaimsPrincipal ValidateToken(string token)
        {
            var config = ConfigHelper.GetOptions<JwtConfig>("Jwt");
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.UTF8.GetBytes(config.SecurityKey);

            try
            {
                var principal = tokenHandler.ValidateToken(token, new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = config.Issuer,
                    ValidateAudience = true,
                    ValidAudience = config.Audience,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ClockSkew = TimeSpan.Zero // 严格校验过期时间
                }, out _);

                return principal;
            }
            catch (SecurityTokenException)
            {
                return null;
            }
        }
    }
}
